import {
  getInfo
} from '../../api/admin/template'
import {
  mapping
} from './mapping'
import * as infoType from '../formHeader/info'
import {
  remote,
  getIdByTableName
} from '../../api/admin/dict' //字典

import {
  getRoleInfo
} from '../../api/admin/template'

import {
  Message
} from 'element-ui'

import store from '../../store'

/**
 * 添加自定义字段
 * type1:新增时使用控件
 * dicData1:新增时数据源
 * @param {*} option 
 * @param {*} funcId 
 * @param {*} that 
 * @param {*} span 
 */
export const updateOption = (option, funcId, that, span, orgId) => {

  const length = option.column.length
  getInfo({
    funcId: mapping[funcId]
  }).then(res => {
    const data = res.data.data
    if (Array.isArray(data)) {
      data.some((res, index) => {
        option.column.push({
          label: res.fieldName,
          prop: `id_${length + index}`,
          hide: true,
          span: span || 12,
          // 新增时使用id
          id: res.id,
          // 类型
          type1: getControlTypes(infoType.mapping[res.fieldType][res.dataType].element, infoType.mapping[res.fieldType][res.dataType].type),
          dicData1: getSourceData({
            paramId: res.customDataJson || res.dictIdName,
            orgId: orgId
          })
        })
      })
    }
  })
  return option
}

/**
 * 解析控件类型
 * @param {*} element 
 * @param {*} type 
 */
const getControlTypes = (element, type) => {
  if (type) {
    let result = ''
    if (type === 'textarea') result = 'textarea'
    return result
  } else {
    return element
  }
}

/**
 * 解析数据来源
 * @param {*} str 
 */
const getSourceData = (str) => {
  let result = []
  try {
    result = JSON.parse(str)
  } catch (error) {
    remote(str).then(res => {
      result.push({
        label: res.label,
        value: res.id
      })
    })
  }
  return result
}

/**
 * 解析数据
 * type2:修改时控件类型->根据新增时使用的控件类型加载
 * dicdata2:修改时数据源
 * @param {*} data 
 * @param {*} object 
 * @param {*} option 
 */
export const analysisData = (data, object, option) => {
  const result = {}
  result[object] = []
  result.list = []
  if (Array.isArray(data)) {
    data.some(res => {
      let index = 0
      // 自定义字段赋值
      option.column.some(res2 => {
        if (res2.prop.indexOf('id_') !== -1) {
          // 设置默认值
          if (typeof (res[1][index]) !== 'undefined') {
            let value = res[1][index].fieldVal || res[1][index].defaultVal
            try {
              value = JSON.parse(value)
            } catch (error) {
              console.error(error)
            }
            res[0][res2.prop] = value
            res2.type2 = getControlTypes(infoType.mapping[res[1][index].fieldType][res[1][index].dataType].element, infoType.mapping[res[1][index].fieldType][res[1][index].dataType].type)
            res2.dicData2 = getSourceData({
              paramId: res[1][index].customDataJson || res[1][index].dictIdName,
              orgId: orgId
            })
          }
          index++
        }
      })
      result[object].push(res[0])
      result.list.push(res[1])
    })
  }
  return result
}

/**
 * 解析修改数据
 * @param {*} data 
 * @param {*} row 
 * @param {*} option 
 * @param {*} object 
 */
export const confirmOption = (data, row, option, object) => {
  const result = {}
  result[object] = row
  result.list = []
  let index = 0
  for (const k in row) {
    // 查询到自定义字段值
    if (k.indexOf('id_') !== -1 && k.indexOf('$') === -1) {
      //可以找到修改id
      if (data.list[row.$index] && data.list[row.$index].length > 0) {
        result.list.push({
          fieldVal: JSON.stringify(row[k]),
          id: data.list[row.$index][index].id
        })
      } else {
        //如果没有查询到修改id
        result.list.push({
          fieldVal: JSON.stringify(row[k]),
          id: option.column[k.split('_')[1]].id
        })
      }
      index++
    }
  }
  return result
}

/**
 * 根据用户权限修改字段属性（是否可见、是否可修改）
 * @param {*} tableName 
 * @param {*} option 
 */
export const updateRole = (tableName, option) => {
  getIdByTableName(tableName).then(res => {
    if (res.data.data) {
      const userId = store.getters.userInfo.userId
      if (!userId) {
        Message.error('用户权限id错误，请检查')
        return
      }
      getRoleInfo({
        funcId: res.data.data.busiFuncId,
        roleId: userId
      }).then(res => {
        const data = res.data.data
        if (Array.isArray(data)) {
          data.some(res2 => {
            option.column.some(res3 => {
              if (`${res2.fieldId}` === `${res3.prop}` || (res3.prop.indexOf('id_') !== -1 && `${res3.id}` === `${res2.fieldId}`)) {
                if (res2.isVisible === 0) {
                  res3.display = false
                  res3.hide = true
                }
                if (res2.isEditable === 0) {
                  res3.readonly = true
                  res3.disabled = true
                  res3.isEditable = false
                }
                return true
              }
            })
          })
        }
      })
    }
  })
}

/**
 * 根据当前弹框类型加载不同控件
 * @param {*} type 
 * @param {*} option 
 */
export const changeTypeByDialog = (type, option) => {
  option.column.some(res => {
    if (res.prop.indexOf('id_') !== -1) {
      if (type === 'add') {
        res.type = res.type1
        res.dicData = res.dicData1
      } else {
        res.type = res.type2
        res.dicData = res.dicData2
      }
    }
  })
}

/**
 * 
 * @param {*} tableName 
 */
export function getIdByTable(tableName) {
  return new Promise((resolve, reject) => {
    getIdByTableName(tableName).then(res => {
      resolve(res.data.data)
    })
  })
}
